package com.chulianyuang.controller;

import com.chulianyuang.mapper.EmployeeMapper;
import com.chulianyuang.pojo.ClaimVoucher;
import com.chulianyuang.pojo.ClaimVoucherDetail;
import com.chulianyuang.pojo.Employee;
import com.chulianyuang.service.ClaimVoucherService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ClaimVoucherController {
    @Autowired
    private ClaimVoucherService claimVoucherService;
    @Autowired
    private EmployeeMapper employeeMapper;

    ClaimVoucher  claimVoucher=new ClaimVoucher();

    /**
     * 查看报销单头
     * @param request
     * @param model
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping("findVoucher")
    public String findVoucher(HttpServletRequest request, Model model,
                              @RequestParam(defaultValue = "1")Integer pageNo,@RequestParam(defaultValue = "5") Integer pageSize) {
        //        开启分页
        PageHelper.startPage(pageNo,pageSize);
        //从会话中获取登录信息
        Employee employee = (Employee) request.getSession().getAttribute("emp");
        if(employee.getPosition_id()==1){
            claimVoucher.setCreate_sn(employee.getSn());
        }else {
            claimVoucher.setNext_deal_sn(employee.getSn());
        }
        List<ClaimVoucher> list =claimVoucherService.selectClaimVoucherBySn(claimVoucher);
//        对集合进行分页包装
        PageInfo<ClaimVoucher> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "jsp/claim/claim_voucher_list";


    }

    /**
     * 添加报销单
     * @param claimVoucher
     * @param session
     * @return
     */
    @RequestMapping("addVoucher")
    public String addClaimVoucher(@ModelAttribute ClaimVoucher claimVoucher, HttpSession  session) {

        //从会话中读取登录人
        Employee employee = (Employee) session.getAttribute("emp");
        List<Employee> employees=employeeMapper.findNextById(employee.getDepartment_id());
//        claimVoucher.setNext_deal_sn();
        claimVoucher.setNext_deal_sn(employees.get(0).getSn());
        claimVoucher.setCreate_sn(employee.getSn());
//        System.out.println( claimVoucher+"111111111111111111111111111111111111111111111111");
//        System.out.println(employee+"2222222222222222222222222222222222222222222222");
        boolean flag=claimVoucherService.addClaimVoucher(claimVoucher);
        return "forward:findVoucher";
    }

    /**
     * 查看报销单详情
     * @param voucherid
     * @param model
     * @return
     */
    @RequestMapping("findVoucherById")
    public String findClaimVoucherByid(Integer voucherid,Model model) {
        ClaimVoucher voucher= claimVoucherService.selectClaimVoucherById(voucherid);
//        System.out.println(voucher+"1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
        model.addAttribute("voucher",voucher);
        return "jsp/claim/claim_voucher_view";
    }

    /**
     * 删除表记录
     * @param voucherid
     * @return
     */
    @RequestMapping("delVoucher")
    public String deleteClaimVoucher(int voucherid) {
        boolean flag=claimVoucherService.deleteClaimVoucherById(voucherid);
    return "forward:findVoucher";

    }

    /**
     * 跳转到更新页面
     */
    @RequestMapping("claimVoucher_toUpdate_action")
    public String toUpdate(@RequestParam("id") Integer id, Model model) {
        try {
            // 根据ID查询报销单详细信息
            ClaimVoucher claimVoucher = claimVoucherService.selectClaimVoucherById(id);
            System.out.println(claimVoucher+"`````````````````````````````````````````````````````````````````````````````````````````````````````");
            model.addAttribute("claimVoucher", claimVoucher);
            return "jsp/claim/claim_voucher_update";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    @RequestMapping("claimVoucher_updateClaimVoucher_action")
    public String updateClaimVoucher(@ModelAttribute ClaimVoucher claimVoucher,
                                     HttpSession session,
                                     Model model) {
        try {
            // 1. 用户认证
            Employee employee = (Employee) session.getAttribute("emp");
            if (employee == null) {
                return "redirect:/login";
            }

            System.out.println("=== 开始更新报销单 ===");
            System.out.println("报销单ID: " + claimVoucher.getId());
            System.out.println("当前状态: " + claimVoucher.getStatus());
            System.out.println("事由: " + claimVoucher.getEvent());
            System.out.println("明细数量: " + (claimVoucher.getDetailList() != null ? claimVoucher.getDetailList().size() : 0));

            // 2. 数据验证
            if (claimVoucher.getDetailList() == null || claimVoucher.getDetailList().isEmpty()) {
                model.addAttribute("error", "至少需要一条报销明细");
                return reloadUpdatePage(claimVoucher.getId(), model);
            }

            // 3. 重新计算总金额
            double totalAmount = 0;
            for (ClaimVoucherDetail detail : claimVoucher.getDetailList()) {
                if (detail.getAccount() != null) {
                    totalAmount += detail.getAccount().doubleValue();
                }
                // 设置明细关联ID
                detail.setMainId(claimVoucher.getId());
            }
            claimVoucher.setTotal_account(totalAmount);
            System.out.println("重新计算的总金额: " + totalAmount);

            // 4. 根据状态设置下一步处理人
            String originalNextDealer = claimVoucher.getNext_deal_sn();
            if ("已提交".equals(claimVoucher.getStatus())) {
                // 提交审批：设置下一步处理人
                List<Employee> managers = employeeMapper.findNextById(employee.getDepartment_id());
                if (managers != null && !managers.isEmpty()) {
                    claimVoucher.setNext_deal_sn(managers.get(0).getSn());
                    System.out.println("设置下一步处理人: " + managers.get(0).getSn() + " (原处理人: " + originalNextDealer + ")");
                }
            } else {
                // 保存草稿：下一步处理人是自己
                claimVoucher.setNext_deal_sn(employee.getSn());
                System.out.println("保存草稿，下一步处理人: " + employee.getSn());
            }


            System.out.println("准备更新数据库...");
             boolean success = claimVoucherService.updateClaimVoucher(claimVoucher);

            System.out.println("更新结果: " + success);

            if (success) {
                System.out.println("更新成功，跳转到列表页111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
                model.addAttribute("message", "报销单更新成功！");
                return "forward:findVoucher";
            } else {
                System.out.println("更新失败，返回更新页面");
                model.addAttribute("error", "报销单更新失败");
                return reloadUpdatePage(claimVoucher.getId(), model);
            }

        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "系统错误: " + e.getMessage());
            return reloadUpdatePage(claimVoucher.getId(), model);
        }
    }

    private String reloadUpdatePage(Integer voucherId, Model model) {
        ClaimVoucher voucher = claimVoucherService.selectClaimVoucherById(voucherId);
        model.addAttribute("claimVoucher", voucher);
        return "jsp/claim/claim_voucher_update";
    }

}
